//1.有的node版本并不支持 es6(import)，所以使用node.js CommonJS
// const redux = require('redux');

//非要使用importe/export可以配置  package.json -> "type": "module",
import redux from "redux";

//2.初始化数据
const initialState = {
  counter: 0
}

//6.reducer(纯函数)  第一次的state为undefined 所以 = 初始化值
function reducer(state = initialState, action) {
  switch(action.type) {
    case "INCREMENT":
            //因为纯函数的特性 所以这里做一个拷贝 定义一个counter 覆盖掉state里的counter的value
      return {...state, counter: state.counter + 1}
    case "DECREMENT":
      return {...state, counter: state.counter - 1}
    case "DECREMENT":
      return {...state, counter: state.counter - 1}
    case "ADD_NUMBER":
      return {...state, counter: state.counter + action.num}
    case "SUB_NUMBER":
      return {...state, counter: state.counter - action.num}
    default:
      return state
  }
}

//3.store （创建的时候需要传入一个reducer）
const store = redux.createStore(reducer)

//7.订阅store修改
store.subscribe(() => {
  console.log('counter:', store.getState().counter);
})

//4.actions
const action1 = {type: "INCREMENT"};
const action2 = {type: "DECREMENT"};
const action3 = {type: "ADD_NUMBER", num: 5};
const action4 = {type: "SUB_NUMBER", num: 10};

//5.派发
store.dispatch(action1);
store.dispatch(action2);
store.dispatch(action3);
store.dispatch(action4);